#!/usr/bin/python3
# -*- encoding: utf-8 -*-
"""
@File    : celery_tasks.py
@Time    : 2022/6/2 9:13
@Author  : YangXin
@License : Copyright(C) 2022 忆享科技 All rights reserved
@Desc    :
"""
import time

import requests
from blueapps.core.celery.celery import app


# @app.task
# def start_task(request):
#     print(request)
from config import APP_CODE, SECRET_KEY, BK_URL
from home_application.models import TaskRecord


@app.task
def get_task_status(token, biz_id, task_id):
    kwargs = {
        "bk_app_code": APP_CODE,
        "bk_app_secret": SECRET_KEY,
        "bk_token": token,
        "bk_biz_id": biz_id,
        "task_id": task_id,
    }
    uri = f"{BK_URL}/api/c/compapi/v2/sops/get_task_status/"
    while True:
        try:
            res = requests.get(uri, params=kwargs, verify=False, timeout=30).json()
        except requests.exceptions.Timeout as err:
            TaskRecord.objects.filter(task_id=task_id).update(status=TaskRecord.FAILED)
            break
        if res.get("code") == 0:
            TaskRecord.objects.filter(task_id=task_id).update(status=res["data"]["state"])
            if res["data"]["state"] == TaskRecord.FINISHED:
                break
            elif res["data"]["state"] == TaskRecord.FAILED:
                break
            elif res["data"]["state"] == TaskRecord.REVOKED:
                break

            time.sleep(1)
        else:
            TaskRecord.objects.filter(task_id=task_id).update(status=TaskRecord.FAILED)
            break





